
package kalkon;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.text.MessageFormat;
import java.util.ResourceBundle;

/**
 *
 * @author tommz
 */
public class InputModuleLoader {

    private ResourceBundle bundle = ResourceBundle.getBundle("kalkon.messages");

    /**
     * Loads input module impentation from jar file.
     * @param jar Jar file path.
     * @param javaPath Fully qualified path to class.
     * @return
     */
    public InputModule loadModule(String jar, String javaPath) {

        ClassLoader cl = null;

        if ("".equals(jar)) {
            // dont load new jar file
            
            cl = ClassLoader.getSystemClassLoader();

        } else {
            URL url = null;
            try {
                url = new URL(jar);
            } catch (MalformedURLException ex) {
                System.err.println(MessageFormat.format(
                        bundle.getString("ML.bad.jar.url"),
                        jar));
                return null;
            }


            URL[] urls = new URL[]{url};
            cl = new URLClassLoader(urls);
        }
        Class<InputModule> cls = null;
        try {
            cls = (Class<InputModule>) cl.loadClass(javaPath);
        } catch (ClassNotFoundException ex) {
            System.err.println(MessageFormat.format(
                    bundle.getString("ML.cannot.load.module"),
                    javaPath));
            return null;
        } catch (NoClassDefFoundError ex) {
            System.err.println(MessageFormat.format(
                    bundle.getString("ML.cannot.load.module"),
                    javaPath));
            return null;
        }

        InputModule ret = null;
        try {
            ret = cls.newInstance();
        } catch (InstantiationException ex) {
            System.err.println(MessageFormat.format(
                    bundle.getString("ML.cannot.load.module"),
                    javaPath));
            return null;
        } catch (IllegalAccessException ex) {
            System.err.println(MessageFormat.format(
                    bundle.getString("ML.cannot.load.module"),
                    javaPath));
            return null;
        }

        return ret;

    }
}
